from parser import Parser

class Dependencies:
  def __init__(self, root_dir):
    self.__root_dir = root_dir
    self.__libraries = {}

  def find_deps(self, target):
    root_library = self.get_library(target)
    all_deps = {target : root_library}
    while True:
      ori_size = len(all_deps)
      for (lib_name, lib) in all_deps.items():
        for dep in lib.deps:
          full_path = dep
          if dep.startswith(":"):
            full_path = lib.path + dep
          all_deps[full_path] = self.get_library(full_path)
      new_size = len(all_deps)
      if ori_size == new_size:
        break
    return all_deps

  def get_library(self, target):
    sep = target.split(":")
    assert len(sep) == 2, "Target should be //path1/path2:target"
    assert sep[0].startswith("//"), "Target should be //path1/path2:target: " + target
    path = sep[0][1:]
    target_in_path = sep[1]

    build_path = self.__root_dir + path + "/BUILD"
    if build_path in self.__libraries:
      assert target_in_path in self.__libraries[build_path]
      return self.__libraries[build_path][target_in_path]
    parser = Parser(build_path) 
    libraries = parser.parse()
    assert target_in_path in libraries, "Could not find %s in %s" % (target_in_path, build_path)
    for (k, v) in libraries.items():
      v.path = "/" + path
    self.__libraries[build_path] = libraries
    return libraries[target_in_path]
